<template>
  <div class="collection-type">
    <el-form ref="payColMethodFrom" :model="payColMethod" :rules="payColMethodRules" label-width="10em">
      <!--      月度规则-->
      <template v-if="method === 1">
        <el-row>
          <el-col :span="12">
            <el-form-item label="首次回款月份：" prop="monthFirst" key="monthFirst">
              <el-date-picker v-model="payColMethod.monthFirst" type="month" value-format="yyyy-MM" placeholder="请选择"
                              clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总月份数：" prop="monthSum" key="monthSum">
              <el-input-number v-model="payColMethod.monthSum" :controls="false" :min="1" :max="120" step-strictly
                               placeholder="请输入"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="tips">最大可支持输入120个月度</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="每月固定回款日：" prop="monthCollectionDay" key="monthCollectionDay">
              <el-select v-model="payColMethod.monthCollectionDay" placeholder="请选择" clearable filterable>
                <el-option v-for="item in monthlyDaysCollection" :value="item.value" :label="item.label"
                           :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <!--      季度规则-->
      <template v-if="method === 2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="首次回款季度：" prop="quarterFirst" key="quarterFirst">
              <quarter-selector v-model="payColMethod.quarterFirst" placeholder="请选择" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总季度数：" prop="quarterSum" key="quarterSum">
              <el-input-number v-model="payColMethod.quarterSum" :controls="false" :min="1" :max="40" step-strictly
                               placeholder="请输入"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="tips">最大可支持输入40个季度</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="固定回款日：" prop="quarterCollectionDay" key="quarterCollectionDay">
              <div class="quarter-collection-day">
                <span>每个季度第</span>
                <el-input-number v-model="payColMethod.quarterCollectionDay[0]" :controls="false" :min="1" :max="3"
                                 step-strictly
                                 size="mini"/>
                <span>个月，</span>
                <el-input-number v-model="payColMethod.quarterCollectionDay[1]" :controls="false" :min="1" :max="31"
                                 step-strictly
                                 size="mini"/>
                <span>号</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <!--      年度规则-->
      <template v-if="method === 3">
        <el-row>
          <el-col :span="12">
            <el-form-item label="首次回款年份：" prop="yearFirst" key="yearFirst">
              <el-date-picker v-model="payColMethod.yearFirst" type="year" placeholder="请选择" value-format="yyyy"
                              clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总年份数：" prop="yearSum" key="yearSum">
              <el-input-number v-model="payColMethod.yearSum" :controls="false" :min="1" :max="10" step-strictly
                               placeholder="请输入"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="tips">最大可支持输入10个年度</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="固定回款日：" prop="yearCollectionDay" key="yearCollectionDay">
              <el-cascader v-model="payColMethod.yearCollectionDay" :options="monthDayCascade" placeholder="请选择"
                           clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <!--      计算规则-->
      <template v-if="method !== 0">
        <el-row>
          <el-col :span="24">
            <el-form-item label="计算规则：" prop="calculationRules">
              <el-radio-group :value="payColMethod.calculationRules" @input="handleChangeCalculationRules">
                <el-radio :label="1">自定义</el-radio>
                <el-radio :label="2">均分</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--      回款计划详情表格-->
      <el-row>
        <el-col :span="21">
          <PayColSchInfo ref="PayColSchInfo" :method="method" :rule="payColMethod.calculationRules" :columns="columns"
                         :info="payColMethod" :main="main"></PayColSchInfo>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
/**
 * 回款方式表单原始对象
 *   originPayColMethod: {
 *   @param calculationRules [number]               // 计算规则（1-自定义 2-均分）
 *   @param collectionMethod [number]               // 回款方式（0-自定义 1-月度 2-季度 3-年度）
 *   // 月度规则
 *   @param monthCollectionDay [number],            // 每月固定回款日
 *   @param monthFirst [number],                    // 首次回款月份
 *   @param monthSum [number],                      // 总月份数
 *   // 季度规则
 *   @param quarterCollectionDay [Array<string>],   // 每季度固定回款日
 *   @param quarterFirst: [Array<string>],          // 首次回款季度
 *   @param quarterSum: [number],                   // 总季度数
 *   // 年度规则
 *   @param yearCollectionDay [string],             // 每年固定回款日
 *   @param yearFirst [number],                     // 首次回款年份
 *   @param yearSum [number],                       // 总年份数
 * }
 */

import {monthDayCascade, monthlyDaysCollection} from '../common/dict'
import QuarterSelector from "./QuarterSelector.vue";
import PayColSchInfo from './PayColSchInfo.vue'
import {cloneDeep} from "lodash";

// 原始表单数据
const originForm = {
  calculationRules: 1,
  collectionMethod: 0
}
// 月度表单数据
const originMonth = {
  collectionMethod: 1,
  monthCollectionDay: null,
  monthFirst: null,
  monthSum: null,
}
// 季度表单数据
const originQuarter = {
  collectionMethod: 2,
  quarterCollectionDay: [],
  quarterFirst: [],
  quarterSum: null,
}
// 年度表单数据
const originYear = {
  collectionMethod: 3,
  yearCollectionDay: null,
  yearFirst: null,
  yearSum: null,
}
export default {
  name: "CollectionType",
  components: {QuarterSelector, PayColSchInfo},
  props: {
    // 回款方式（0-自定义 1-月度 2-季度 3-年度）
    method: {
      required: true,
      type: Number
    },
    // 回款基本信息表单
    main: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      // 回款方式表单
      payColMethod: {},
      // 表单验证规则
      payColMethodRules: {
        monthFirst: {required: true, message: '请选择首次回款月份', trigger: 'change'},
        monthSum: {required: true, message: '请输入月份总数', trigger: 'change'},
        monthCollectionDay: {required: true, message: '请选择每月固定还款日', trigger: 'change'},
        quarterFirst: {required: true, message: '请选择首次回款季度', trigger: 'change'},
        quarterSum: {required: true, message: '请输入季度总数', trigger: 'change'},
        quarterCollectionDay: {required: true, validator: this.checkQuarterCollectionDay, trigger: 'blur'},
        yearFirst: {required: true, message: '请选择首次回款月份', trigger: 'change'},
        yearSum: {required: true, message: '请输入月份总数', trigger: 'change'},
        yearCollectionDay: {required: true, message: '请选择固定还款日', trigger: 'change'},
        calculationRules: {required: true}
      },
      // 月份总天数
      monthlyDaysCollection,
      // 月日级联选择器数据
      monthDayCascade,
    }
  },
  computed: {
    columns() {
      return this.payColMethod.monthSum || this.payColMethod.quarterSum || this.payColMethod.yearSum || 0
    }
  },
  watch: {
    method: {
      handler(n) {
        switch (n) {
          case 0:
            this.$set(this, 'payColMethod', {...JSON.parse(JSON.stringify(originForm))})
            break;
          case 1:
            this.$set(this, 'payColMethod', {...originForm, ...JSON.parse(JSON.stringify(originMonth))})
            break;
          case 2:
            this.$set(this, 'payColMethod', {...originForm, ...JSON.parse(JSON.stringify(originQuarter))})
            break;
          case 3:
            this.$set(this, 'payColMethod', {...originForm, ...JSON.parse(JSON.stringify(originYear))})
            break;
          default:
            return new Error('传递的type有误 回款方式：（0-自定义 1-月度 2-季度 3-年度）')
        }
        this.$nextTick(() => {
          this.$refs.payColMethodFrom.clearValidate()
        })
      },
      immediate: true
    },
  },
  methods: {
    // 验证季度固定还款日
    checkQuarterCollectionDay(rule, value, callback) {
      const arr = this.payColMethod.quarterCollectionDay
      if (arr instanceof Array && arr.filter(i => i).length === 2) {
        callback()
      } else {
        callback(new Error('请输入固定还款日'))
      }
    },

    // 切换计算规则时弹出提示
    handleChangeCalculationRules(label) {
      if (label === 1) {
        this.payColMethod.calculationRules = label
      } else {
        this.$confirm('将计算规则切换为均分将会清空已填写的自定义金额/占比内容，是否确定切换?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.payColMethod.calculationRules = label
        })
      }
    },

    // 触发表单本组件和子组件的表单验证，并返回一个promise
    validateForm() {
      const selfPromise = new Promise((resolve, reject) => {
        this.$refs.payColMethodFrom.validate((valid) => {
          if (valid) {
            resolve(cloneDeep(this.payColMethod))
          } else {
            reject()
          }
        })
      })

      // 触发子组件(PayColSchInfo)的表单验证
      const sonPromise = this.$refs.PayColSchInfo.validateForm()
      return [selfPromise, sonPromise]
    }
  }
}
</script>


<style scoped lang="scss">
.collection-type {
  .tips {
    margin-left: 10px;
    line-height: 36px;
  }

  .quarter-collection-day {
    ::v-deep {
      .el-input-number {
        width: 50px !important;
        margin: 0 5px;

        .el-input__inner {
          text-align: center !important;
        }

      }
    }
  }
}
</style>
